#include <iostream>
#include <mutex>
#include <thread>
#include <random>
#include <memory>
#include <condition_variable>
#include <unistd.h>

using namespace std;
// TODO: C++ 的条件变量又要怎么写呢？？？？
// 怎么使用智能指针呢？？？？
mutex mtx;
condition_variable cv;
typedef struct node{
  int data;
  
  struct unique_ptr<node> next;
}Node;
unique_ptr<node> head(nullptr);

void producer()
{
  std::random_device rd;  // 将用于为随机数引擎获得种子
  std::mt19937 gen(rd()); // 以播种标准 mersenne_twister_engine
  std::uniform_int_distribution<> dis(1, 10000);
  std::uniform_int_distribution<> utime(1, 3);
  while(1)
  {
    unique_ptr<node> pnew = unique_ptr<node>(new(Node));
    pnew->data = dis(gen);
    mtx.lock();
    pnew->next = std::move(head);
    head = std::move(pnew);
    cout << "=====producer thread id " << this_thread::get_id() << " val " << pnew->data << endl; 
    mtx.unlock();
    sleep(utime(gen));
  }


}

void consumer()
{
  while(1)
  {
    if(head == nullptr)
    {
      continue;
    }
    // 开始消费
    unique_ptr<node> pdel = std::move(head);
    mtx.lock();
    head = std::move(head->next);
    cout << "-------consumer thread id " << this_thread::get_id() << " val " << pdel->data << endl;
    mtx.unlock();
  }
}
int main()
{
  thread tr1(producer);
  thread tr2(consumer);
  tr1.join();
  tr2.join();

  return 0;
}
